package cn.calm.xhtml.nature;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.core.resources.ICommand;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IProjectNature;
import org.eclipse.core.runtime.CoreException;

public class XhtmlNature implements IProjectNature{
	public static final String XHTML_NATURE_ID = "cn.calm.xhtml.eclipse.XhtmlNature";
	static final String XHTML_BUILDER_ID = "cn.calm.xhtml.eclipse.XhtmlBuilder";
	private IProject project;
	/**
	 * {@inheritDoc}
	 */
	@Override
	public void configure() throws CoreException {

		// Add the Xhtml builder
		IProjectDescription description = project.getDescription();
		ICommand[] commands = description.getBuildSpec();
		ICommand[] newcommands = new ICommand[commands.length + 1];
		System.arraycopy(commands, 0, newcommands, 0, commands.length);
		ICommand command = description.newCommand();
		command.setBuilderName(XHTML_BUILDER_ID);
		newcommands[commands.length] = command;
		description.setBuildSpec(newcommands);
		project.setDescription(description, null);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void deconfigure() throws CoreException {

		// Remove the Xhtml builder
		IProjectDescription description = project.getDescription();
		ICommand[] commands = description.getBuildSpec();
		List<ICommand> tempNewCommands=new ArrayList<>(commands.length - 1);
		ICommand[] newcommands = new ICommand[commands.length - 1];
		int xhtmlbuilderindex;
		for (xhtmlbuilderindex = 0; xhtmlbuilderindex < commands.length; xhtmlbuilderindex++) {
			if (!commands[xhtmlbuilderindex].getBuilderName().equals(XHTML_BUILDER_ID)) {
				tempNewCommands.add(commands[xhtmlbuilderindex]);
			}
		}
		tempNewCommands.toArray(newcommands);
		description.setBuildSpec(newcommands);
		project.setDescription(description, null);
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public IProject getProject() {

		return project;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setProject(IProject project) {

		this.project = project;
	}

	/**
	 * Check if the Thymeleaf nature has been applied to the given project.
	 * 
	 * @param project
	 * @return <tt>true</tt> if the project has the Thymeleaf nature.
	 */
	public static boolean xhtmlNatureEnabled(IProject project) {

		try {
			return project.hasNature(XHTML_NATURE_ID);
		}
		catch (CoreException ex) {
			// Do nothing
		}
		return false;
	}
}
